﻿using System;
using System.Web.UI;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;

namespace SPPropertyBagManagement.Code
{
    public class PropertyManagementBasePage : LayoutsPageBase
    {
        /// <summary>
        /// Gets or sets the scope.
        /// </summary>
        /// <value>
        /// The scope.
        /// </value>
        protected ScopeType Scope
        {
            get
            {
                return (ScopeType)ViewState["PropertyManagementBasePage_Scope"];
            }

            set
            {
                ViewState["PropertyManagementBasePage_Scope"] = value;
            }
        }

        /// <summary>
        /// Gets or sets the object id.
        /// </summary>
        /// <value>
        /// The object id.
        /// </value>
        protected Guid? ObjectId
        {
            get
            {
                return ViewState["PropertyManagementBasePage_ObjectId"] as Guid?;
            }

            set
            {
                ViewState["PropertyManagementBasePage_ObjectId"] = value;
            }
        }

        /// <summary>
        /// Gets or sets the object id.
        /// </summary>
        /// <value>
        /// The object id.
        /// </value>
        protected int? ListItemObjectId
        {
            get
            {
                return ViewState["PropertyManagementBasePage_ListItemObjectId"] as int?;
            }

            set
            {
                ViewState["PropertyManagementBasePage_ListItemObjectId"] = value;
            }
        }

        /// <summary>
        /// Gets or sets the property name.
        /// </summary>
        /// <value>
        /// The property id.
        /// </value>
        protected string PropertyName
        {
            get
            {
                return ViewState["PropertyManagementBasePage_PropertyName"] as string;
            }

            set
            {
                ViewState["PropertyManagementBasePage_PropertyName"] = value;
            }
        }

        /// <summary>
        /// Represents the method that handles the Init event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            InitParams();

            switch (Scope)
            {
                case ScopeType.ListItem:
                    if (!SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.ManageWeb))
                    {
                        SPUtility.HandleAccessDenied(new Exception("You do not have sufficient permissions to complete this action."));
                    }
                    break;
                case ScopeType.List:
                    if (!SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.ManageLists))
                    {
                        SPUtility.HandleAccessDenied(new Exception("You do not have sufficient permissions to complete this action."));
                    }
                    break;
                case ScopeType.Web:
                    if (!SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.ManageWeb))
                    {
                        SPUtility.HandleAccessDenied(new Exception("You do not have sufficient permissions to complete this action."));
                    }
                    break;
                case ScopeType.WebApplication:
                    if (!SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.FullMask))
                    {
                        SPUtility.HandleAccessDenied(new Exception("You do not have sufficient permissions to complete this action."));
                    }
                    break;
                case ScopeType.Farm:
                    if (!SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.FullMask))
                    {
                        SPUtility.HandleAccessDenied(new Exception("You do not have sufficient permissions to complete this action."));
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Inits the params.
        /// </summary>
        /// <exception cref="Microsoft.SharePoint.SPException">No property id defined.</exception>
        private void InitParams()
        {
            var scopeValue = Request.QueryString["Scope"];
            var idValue = Request.QueryString["Id"];
            var propName = Request.QueryString["PropertyName"];
            var liIdValue = Request.QueryString["ItemId"];

            if (scopeValue == null || scopeValue.Trim().Length == 0)
            {
                throw new SPException("No scope defined.");
            }

            scopeValue = scopeValue.Trim().ToLower();

            if (scopeValue == "farm")
            {
                Scope = ScopeType.Farm;
            }
            else if (scopeValue == "web")
            {
                Scope = ScopeType.Web;
            }
            else if (scopeValue == "list")
            {
                Scope = ScopeType.List;

                if (idValue == null || idValue.Trim().Length == 0)
                {
                    throw new SPException("No Id defined for scope List.");
                }

                ObjectId = ResolveObjectId(idValue);
            }
            else if (scopeValue == "webapplication")
            {
                Scope = ScopeType.WebApplication;

                if (idValue == null || idValue.Trim().Length == 0)
                {
                    throw new SPException("No Id defined for scope WebApplication.");
                }

                ObjectId = ResolveObjectId(idValue);
            }
            else if (scopeValue == "listitem")
            {
                Scope = ScopeType.ListItem;

                if (idValue == null || idValue.Trim().Length == 0)
                {
                    throw new SPException("No Id defined for scope ListItem.");
                }

                if (liIdValue == null || liIdValue.Trim().Length == 0)
                {
                    throw new SPException("No ItemId defined for scope ListItem.");
                }

                ObjectId = ResolveObjectId(idValue);
                ListItemObjectId = ResolveListItemObjectId(liIdValue);
            }
            else
            {
                throw new SPException("Invalid parameters.");
            }

            PropertyName = propName;
        }

        /// <summary>
        /// Resolves the object id.
        /// </summary>
        /// <param name="idValue">The id value.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        private Guid? ResolveObjectId(string idValue)
        {
            if (idValue == null)
            {
                return null;
            }

            try
            {
                return new Guid(idValue.Trim());
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// Resolves the object id.
        /// </summary>
        /// <param name="idValue">The id value.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        private int? ResolveListItemObjectId(string idValue)
        {
            if (idValue == null)
            {
                return null;
            }

            try
            {
                return int.Parse(idValue.Trim());
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// Finds the control.
        /// </summary>
        /// <param name="controlCollection">The control collection.</param>
        /// <param name="controlId">The control id.</param>
        /// <returns></returns>
        public Control FindControl(ControlCollection controlCollection, string controlId)
        {
            return Utils.FindControl(controlCollection, controlId);
        }

        /// <summary>
        /// Sets the page title.
        /// </summary>
        /// <param name="title">The title.</param>
        public void SetPageTitle(string title)
        {
            Utils.SetPageTitle(Page, title);
        }

        /// <summary>
        /// Sets the page sub title.
        /// </summary>
        /// <param name="title">The title.</param>
        public void SetPageSubTitle(string title)
        {
            Utils.SetPageSubTitle(Page, title);
        }

        /// <summary>
        /// Closes the dialog.
        /// </summary>
        /// <param name="dialogResult">The dialog result.</param>
        /// <param name="returnValue">The return value.</param>
        /// <param name="message">The message.</param>
        public void CloseDialog(int dialogResult, string returnValue, string message)
        {
            Page.Response.Write("<script type=\"text/javascript\">window.frameElement.commonModalDialogClose(" + dialogResult + ", '" + returnValue + "');</script>");
        }
    }
}
